<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';

// 定义画布引用
const canvasRef = ref<HTMLCanvasElement | null>(null);
// 定义绘图上下文
let ctx: CanvasRenderingContext2D | null = null;
// 定义是否正在绘图的标志
let isDrawing = false;
// 定义笔触颜色，默认黑色
const stroke_color = ref<string>('black');
// 定义笔触大小，默认 5
const stroke_size = ref<number>(5);
// 定义存储笔画路径的数组
const strokes = ref<{ points: { x: number; y: number }[]; color: string; size: number }[]>([]);
// 定义当前笔画的点数组
let currentStroke: { points: { x: number; y: number }[]; color: string; size: number } = {
  points: [],
  color: stroke_color.value,
  size: stroke_size.value
};

// 挂载时初始化画布和监听窗口大小变化
onMounted(() => {
  if (canvasRef.value) {
    ctx = canvasRef.value.getContext('2d');
    if (ctx) {
      resizeCanvas();
      ctx.lineCap = 'round';
      ctx.lineJoin = 'round';
    }
  }
  window.addEventListener('resize', handleResize);
});

// 卸载时移除窗口大小变化监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
});

// 调整画布大小并重新绘制
const resizeCanvas = () => {
  if (canvasRef.value && ctx) {
    canvasRef.value.width = window.innerWidth * 0.8;
    canvasRef.value.height = window.innerHeight * 0.7;
    ctx.clearRect(0, 0, canvasRef.value.width, canvasRef.value.height);
    redrawStrokes();
  }
};

// 处理窗口大小变化事件
const handleResize = () => {
  resizeCanvas();
};

// 开始绘图
const startDrawing = (e: MouseEvent) => {
  isDrawing = true;
  currentStroke = {
    points: [],
    color: stroke_color.value,
    size: stroke_size.value
  };
  const { offsetX, offsetY } = e;
  currentStroke.points.push({ x: offsetX, y: offsetY });
};

// 绘图过程
const draw = (e: MouseEvent) => {
  if (isDrawing && ctx) {
    const { offsetX, offsetY } = e;
    currentStroke.points.push({ x: offsetX, y: offsetY });
    ctx.strokeStyle = currentStroke.color;
    ctx.lineWidth = currentStroke.size;
    ctx.beginPath();
    ctx.moveTo(currentStroke.points[currentStroke.points.length - 2].x, currentStroke.points[currentStroke.points.length - 2].y);
    ctx.lineTo(offsetX, offsetY);
    ctx.stroke();
  }
};

// 停止绘图
const stopDrawing = () => {
  if (isDrawing && currentStroke.points.length > 0) {
    strokes.value.push(currentStroke);
  }
  isDrawing = false;
};

// 回退笔画
const undo = () => {
  if (strokes.value.length > 0) {
    strokes.value.pop();
    if (ctx) {
      ctx.clearRect(0, 0, canvasRef.value?.width || 0, canvasRef.value?.height || 0);
      redrawStrokes();
    }
  }
};

// 重绘所有笔画
const redrawStrokes = () => {
  if (ctx) {
    strokes.value.forEach((stroke) => {
      ctx!.strokeStyle = stroke.color;
      ctx!.lineWidth = stroke.size;
      ctx!.beginPath();
      ctx!.moveTo(stroke.points[0].x, stroke.points[0].y);
      for (let i = 1; i < stroke.points.length; i++) {
        ctx!.lineTo(stroke.points[i].x, stroke.points[i].y);
      }
      ctx!.stroke();
    });
  }
};

// 清除画布
const clear = () => {
  if (ctx) {
    ctx.clearRect(0, 0, canvasRef.value?.width || 0, canvasRef.value?.height || 0);
    strokes.value = [];
  }
};

// 导出为 PNG 文件
const exportAsPNG = () => {
  if (canvasRef.value) {
    const timestamp = new Date().getTime();
    const dataURL = canvasRef.value.toDataURL('image/png');
    const link = document.createElement('a');
    link.href = dataURL;
    link.download = `signature-${timestamp}.png`;
    link.click();
  }
};
</script>

<template>
  <div class="signature_board_container">
    <div class="canvas_wrapper">
      <canvas ref="canvasRef" @mousedown="startDrawing" @mousemove="draw" @mouseup="stopDrawing" @mouseout="stopDrawing"></canvas>
    </div>
    <div class="controls_wrapper">
      <div class="controls_left">
        <div class="control_group">
          <label for="color_picker">笔触颜色:</label>
          <input type="color" id="color_picker" v-model="stroke_color" />
        </div>
        <div class="control_group">
          <label for="size_range">笔触大小:</label>
          <input type="range" id="size_range" min="1" max="20" v-model="stroke_size" />
        </div>
      </div>
      <div class="controls_right">
        <button class="undo_button" @click="undo">回退</button>
        <button class="clear_button" @click="clear">清除</button>
        <button class="export_button" @click="exportAsPNG">导出为 PNG</button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.signature_board_container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.canvas_wrapper {
  border: 2px solid #333;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  width: 100%; /* 让画布容器宽度自适应窗口 */
}

.canvas_wrapper canvas {
  width: 100%;
  height: 100%;
}

.controls_wrapper {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.controls_left {
  display: flex;
  flex-direction: row;
  gap: 10px;
}

.control_group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.control_group label {
  font-size: 16px;
  font-weight: 600;
}

.control_group input[type="color"] {
  width: 40px;
  height: 40px;
  border: none;
  cursor: pointer;
}

.control_group input[type="range"] {
  width: 150px;
}

.controls_right {
  display: flex;
  gap: 10px;
}

.undo_button {
  padding: 10px 20px;
  font-size: 16px;
  background-color: #FF4040; /* 珊瑚红，可根据喜好修改 */
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.undo_button:hover {
  background-color: #FF1A1A;
}

.clear_button {
  padding: 10px 20px;
  font-size: 16px;
  background-color: #DC3545;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.clear_button:hover {
  background-color: #C82333;
}

.export_button {
  padding: 10px 20px;
  font-size: 16px;
  background-color: #007BFF;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.export_button:hover {
  background-color: #0056b3;
}
</style>